package com.zhsj.OkeHomeConsumption.ui.activity;

import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdate;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.LatLngBounds;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.SuggestionCity;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.InputtipsQuery;
import com.amap.api.services.help.Tip;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.zhsj.OkeHomeConsumption.R;
import com.zhsj.OkeHomeConsumption.common.MyActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * author : Xingdx
 * <p>
 * time   : 2018/10/18
 * desc   : 地图页面
 */
public final class MapActivity extends MyActivity implements LocationSource, AMapLocationListener
        , PoiSearch.OnPoiSearchListener, AMap.OnMyLocationChangeListener, GeocodeSearch.OnGeocodeSearchListener, AMap.InfoWindowAdapter, AMap.OnMapClickListener,
        AMap.OnMapLongClickListener, AMap.OnCameraChangeListener, Inputtips.InputtipsListener , TextWatcher {

    MapView map;

    @BindView(R.id.recy_map)
    RecyclerView recyMap;

    @BindView(R.id.ren_sure)
    RelativeLayout renSure;

    @BindView(R.id.verificationCode)
    AutoCompleteTextView verificationCode;

    //初始化地图控制器对象
    private AMap aMap;

    private MyLocationStyle myLocationStyle;

    private OnLocationChangedListener mListener;

    private ImageView nack_img;

    // 选择的地址
    private String chooseAddress = "";

    private String city = "";//搜索城市

    private Marker marker;

    private LatLonPoint latLonPoint;

    private String keyWord;

    private MarkerOptions markerOption;

    private LatLng latlng;

    private int Page = 0;// 当前页面，从0开始计数
    private PoiSearch.Query query;// Poi查询条件类
    private int currentPage = 0;// 当前页面，从0开始计数
    private PoiSearch poiSearch;
    private PoiResult poiResult; // poi返回的结果
    private List<PoiItem> poiItems;// poi数据
    private LatLonPoint lp;//

    private MapAdapter mapAdapter;

    private double latitude = 0;//纬度

    private double longitude = 0;//经度

    private String name = "";

    @Override
    protected int getLayoutId() {
        return R.layout.activity_map;
    }

    @Override
    protected int getTitleId() {
        return R.id.tb_copy_title;
    }

    @Override
    protected void initView() {
        nack_img = findViewById(R.id.nack_img);
        map = findViewById(R.id.map);
        if (aMap == null) {
            aMap = map.getMap();
        }
    }

    @Override
    protected void initData() {
        verificationCode.addTextChangedListener(this);// 添加文本输入框监听事件
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        //设置布局管理器
        recyMap.setLayoutManager(layoutManager);
        //设置为垂直布局，这也是默认的
        layoutManager.setOrientation(OrientationHelper.VERTICAL);
        aMap.setOnMapClickListener(this);// 对amap添加单击地图事件监听器
        aMap.setOnMapLongClickListener(this);// 对amap添加长按地图事件监听器
        aMap.setOnCameraChangeListener(this);// 对amap添加移动地图事件监听器
        myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);//定位一次，且将视角移动到地图中心点。
        myLocationStyle.interval(2000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        myLocationStyle.showMyLocation(true);//设置是否显示定位小蓝点，用于满足只想使用定位，不想使用定位小蓝点的场景，设置false以后图面上不再有定位蓝点的概念，但是会持续回调位置信息。

        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        aMap.getUiSettings().setMyLocationButtonEnabled(true);//设置默认定位按钮是否显示，非必需设置。
        aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
        CameraUpdate mCameraUpdate = CameraUpdateFactory.zoomTo(17);
        aMap.moveCamera(mCameraUpdate);
        aMap.setOnMyLocationChangeListener(this);

        Intent intent = getIntent();
        if(intent.getStringExtra("latitude")!=null){
            latitude = Double.parseDouble(intent.getStringExtra("latitude"));
            longitude = Double.parseDouble(intent.getStringExtra("longitude"));
            name = intent.getStringExtra("shopLocation");
        }
        renSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent data = new Intent();
                Bundle bundle = new Bundle();
                bundle.putSerializable("latitude", String.valueOf(latitude));
                bundle.putSerializable("longitude", String.valueOf(longitude));
                bundle.putSerializable("name", name);
                data.putExtras(bundle);
                setResult(RESULT_OK, data);
                finish();

            }
        });

        nack_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    /**
     * 在地图上添加marker
     */
    private void addMarkersToMap() {
        if (latitude != 0 && longitude != 0) {
            latlng = new LatLng(latitude, longitude);
            markerOption = new MarkerOptions().icon(BitmapDescriptorFactory
                    .defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
                    .position(latlng)
                    .title("s")
                    .snippet(name)
                    .draggable(true);
        } else {
            markerOption = new MarkerOptions().icon(BitmapDescriptorFactory
                    .defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
                    .position(latlng)
                    .snippet("")
                    .draggable(true);
        }


        aMap.addMarker(markerOption);
    }

    /**
     * 开始进行poi搜索
     */
    /**
     * 开始进行poi搜索
     */
    protected void doSearchQuery(LatLonPoint lp) {
        currentPage = 0;
        query = new PoiSearch.Query(keyWord, "", city);// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
        query.setPageSize(20);// 设置每页最多返回多少条poiitem
        query.setPageNum(currentPage);// 设置查第一页

        if (lp != null) {
            poiSearch = new PoiSearch(this, query);
            poiSearch.setOnPoiSearchListener(this);
            poiSearch.setBound(new PoiSearch.SearchBound(lp, 5000, true));
            // 设置搜索区域为以lp点为圆心，其周围5000米范围
            poiSearch.searchPOIAsyn();// 异步搜索
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        //在activity执行onCreate时执行map.onCreate(savedInstanceState)，创建地图
        map.onCreate(savedInstanceState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行map.onDestroy()，销毁地图
        map.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行map.onResume ()，重新绘制加载地图
        map.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行map.onPause ()，暂停地图的绘制
        map.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行map.onSaveInstanceState (outState)，保存地图当前的状态
        map.onSaveInstanceState(outState);
    }

    //获取经纬度信息
    @Override
    public void onMyLocationChange(Location location) {
        //从location对象中获取经纬度信息，地址描述信息，建议拿到位置之后调用逆地理编码接口获取（获取地址描述数据章节有介绍）
        location.toString();
        latlng = new LatLng(location.getLatitude(), location.getLongitude());
        addMarkersToMap();
        lp = new LatLonPoint(location.getLatitude(), location.getLongitude());

        doSearchQuery(lp);

    }

    //通过经纬度查找地址的回调方法
    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {

    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {

    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {

    }

    @Override
    public void deactivate() {

    }

    @Override
    public View getInfoWindow(Marker marker) {
        return null;
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    /**
     * 对单击地图事件回调
     */
    @Override
    public void onMapClick(LatLng latLng) {

    }

    @Override
    public void onPoiSearched(PoiResult result, int rcode) {
        if (rcode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getQuery() != null) {// 搜索poi的结果
                if (result.getQuery().equals(query)) {// 是否是同一条
                    poiResult = result;
                    poiItems = poiResult.getPois();// 取得第一页的poiitem数据，页数从数字0开始
                    List<SuggestionCity> suggestionCities = poiResult
                            .getSearchSuggestionCitys();// 当搜索不到poiitem数据时，会返回含有搜索关键字的城市信息
                    if (poiItems != null && poiItems.size() > 0) {
                        mapAdapter = new MapAdapter(poiItems);
                        recyMap.setAdapter(mapAdapter);
                    } else if (suggestionCities != null
                            && suggestionCities.size() > 0) {
                    } else {

                    }
                }
            } else {

            }
        } else {

        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }

    /**
     * 对正在移动地图事件回调
     */
    @Override
    public void onCameraChange(CameraPosition cameraPosition) {

    }

    /**
     * 对移动地图结束事件回调
     */
    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        if (aMap != null) {
            aMap.clear();
        }
        latlng = new LatLng(cameraPosition.target.latitude, cameraPosition.target.longitude);

        addMarkersToMap();
        lp = new LatLonPoint(cameraPosition.target.latitude, cameraPosition.target.longitude);
        doSearchQuery(lp);
    }

    /**
     * 对长按地图事件回调
     */
    @Override
    public void onMapLongClick(LatLng latLng) {

    }

    /**
     * 移动镜头到当前的视角。
     *
     * @since V2.1.0
     */
    public void zoomToSpan(LatLngBounds.Builder bounds) {

        aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds.build(), 100));
    }


    /**
     * 关键字检索。
     *
     * @since V2.1.0
     */
    @Override
    public void onGetInputtips(final List<Tip> list, int code) {
        if (code == AMapException.CODE_AMAP_SUCCESS) {// 正确返回
            List<String> listString = new ArrayList<String>();
            for (int i = 0; i < list.size(); i++) {
                listString.add(list.get(i).getName());
            }
            ArrayAdapter<String> aAdapter = new ArrayAdapter<String>(
                    getApplicationContext(),
                    R.layout.route_inputs, listString);
            verificationCode.setAdapter(aAdapter);
            verificationCode.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    list.get(position);
                    LatLngBounds.Builder b = LatLngBounds.builder();
                    b.include(new LatLng(list.get(position).getPoint().getLatitude(),
                            list.get(position).getPoint().getLongitude()));
                    latitude = list.get(position).getPoint().getLatitude();//纬度
                    name = list.get(position).getName();
                    longitude = list.get(position).getPoint().getLongitude();//经度
                    zoomToSpan(b);
                }
            });
            aAdapter.notifyDataSetChanged();
        } else {
            toast("查询失败");
            Log.e("地图关键字检索错误：",code+"");
        }

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        String newText = s.toString().trim();
        if (!IsEmptyOrNullString(newText)) {
            InputtipsQuery inputquery = new InputtipsQuery(newText, verificationCode.getText().toString());
            Inputtips inputTips = new Inputtips(this, inputquery);
            inputTips.setInputtipsListener(this);
            inputTips.requestInputtipsAsyn();
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
    public static boolean IsEmptyOrNullString(String s) {
        return (s == null) || (s.trim().length() == 0);
    }
    public class MapAdapter extends BaseQuickAdapter<PoiItem, BaseViewHolder> {
        public MapAdapter(List<PoiItem> poiItems) {
            super(R.layout.item_map, poiItems);
        }

        @Override
        protected void convert(@NonNull BaseViewHolder helper, final PoiItem item) {
            helper.setText(R.id.title_text, item.getTitle())
                    .setText(R.id.city_text, item.getSnippet())
                    .setOnClickListener(R.id.lin, new AdapterView.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            LatLngBounds.Builder b = LatLngBounds.builder();
                            b.include(new LatLng(item.getLatLonPoint().getLatitude(),
                                    item.getLatLonPoint().getLongitude()));
                            latitude = item.getLatLonPoint().getLatitude();//纬度
                            name = item.getSnippet();
                            longitude = item.getLatLonPoint().getLongitude();//经度
                            zoomToSpan(b);
                        }

                    });
        }
    }
}